package com.jimmy.reggie.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jimmy.reggie.common.R;
import com.jimmy.reggie.entity.User;
import com.jimmy.reggie.service.UserService;
import com.jimmy.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        String phoneNumber = user.getPhone();
        if (!StringUtils.isEmpty(phoneNumber)){
            String code= ValidateCodeUtils.generateValidateCode(4).toString();
            log.info(code);
            //调用阿里云的工具类完成发送短信的功能
//             SMSUtils.sendMessage("reggie外卖","",phoneNumber,code);
            //将生成的验证码，保存到session中
            redisTemplate.opsForValue().set("phone",code,5, TimeUnit.MINUTES);
//            session.setAttribute("phone",code);
            return R.success("短信验证码发送成功");
        }
        return  R.error("发送失败");
    }

    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        log.info(map.toString());
        Object phone = map.get("phone").toString();
        Object code = map.get("code").toString();
        Object codeInSession = redisTemplate.opsForValue().get("phone");
//        Object codeInSession = session.getAttribute("phone");
        //开始比对
        if (codeInSession!=null&&codeInSession.equals(code)){
            //开始查具体的用户信息，并且返回
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(userLambdaQueryWrapper);
            if (user==null){
                //自动注册
                user = new User();
                user.setPhone(phone.toString());
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            redisTemplate.delete("phone");
            return R.success(user);
        }
         return R.error("登陆失败");
    }



}
